/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.redis;

import cn.ac.iie.di.wx.common.RuntimeEnv;
import cn.ac.iie.di.wx.startup.Server;
import cn.ac.iie.di.wx.utils.DateUtil;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import javax.swing.text.DateFormatter;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class RedisThread implements Runnable {

    public RedisUtil redisUtil;
    public String key;
    public AtomicInteger value;
    public static Logger logger = Logger.getLogger(RedisThread.class.getName());

    public RedisThread(RedisUtil redisUtil, String key, AtomicInteger value) {
        this.redisUtil = redisUtil;
        this.key = key;
        this.value = value;
    }

    @Override
    public void run() {
        while (true) {
            try {
                //添加redis的更新程序，更新的时间间隔为5分钟一次，写入redis的格式是字段名称_今日日期_当前时间
                //回传计算所，使用get方法将值获取出来，地址和请求响应格式未定
                //从原子变量获取值
                String todayDate = DateUtil.getToDayDate();
                redisUtil.set(key + todayDate, String.valueOf(value.get()));//会释放连接资源，需要验证一下是否可以持续写入
                logger.info("update to redis key " + key + todayDate + ",value is " + redisUtil.get(key + todayDate));
                Thread.sleep(1000 * 60);
                //在这进行发送回传计算所的post
            } catch (InterruptedException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }

    }

    public static void main(String[] args) throws Exception {
        Server.init();
        AtomicInteger value = new AtomicInteger(12);
        System.out.println(String.valueOf(value));
        RedisUtil redisUtil = new RedisUtil((String) RuntimeEnv.getParam(RuntimeEnv.REDIS_HOSTS), (String) RuntimeEnv.getParam(RuntimeEnv.REDIS_MASTER_NAME), Integer.parseInt((String) RuntimeEnv.getParam(RuntimeEnv.REDIS_DB_NAME)));
        String todayDate = DateUtil.getToDayDate();
        SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");//设置日期格式
        String timeNow = df.format(new Date());
        System.out.println(timeNow);
        String key = "nrd_" + todayDate;
        redisUtil.set("nrd_" + todayDate, String.valueOf(value));
        String s = redisUtil.getset(key, String.valueOf(value));//返回上一个旧值，设置一个新值
        System.out.println(s);
//        RedisThread redisThread=new RedisThread(redisUtil, "nrd_" + todayDate+"_"+timeNow, value);

    }
}
